package com.cskaoyan.market.controller;

import com.cskaoyan.market.bo.UpdateCategoryBo;
import com.cskaoyan.market.db.domain.MarketCategory;
import com.cskaoyan.market.service.MarketCategoryService;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.MarketCategoryL1Vo;
import com.cskaoyan.market.vo.MarketCategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @ClassName: AdminCategoryController
 * @Description:
 * @Author: 鲸落
 * @Date: 2024/05/06/21:32
 * @Version: 1.0
 */
@RestController
@RequestMapping("admin/category")
public class AdminCategoryController {
    @Autowired
    private MarketCategoryService marketCategoryService;
    @GetMapping("list")
    public Object list(){
        List<MarketCategoryVo> marketCategoryVoList = marketCategoryService.list();
        return ResponseUtil.okList(marketCategoryVoList);
    }
    @GetMapping("l1")
    public Object l1() {
        List<MarketCategoryL1Vo> marketCategoryL1VoList = marketCategoryService.l1();
        return  ResponseUtil.okList(marketCategoryL1VoList);
    }
    @PostMapping("delete")
    public Object delete(@RequestBody MarketCategoryVo requestCategoryVo) {
        // 请求体是json字符串，且分析后可知类型为MarketCategoryVo
        marketCategoryService.delete(requestCategoryVo);
        return ResponseUtil.ok();
    }
    @PostMapping("update")
    public Object update(@RequestBody UpdateCategoryBo updateCategoryBo) {
        // 参数校验
        List<MarketCategoryVo> children = updateCategoryBo.getChildren();
        String level = updateCategoryBo.getLevel();
        // 修改为二级类目时参数会出问题
        if("L2".equals(level)){
            //  父类目不能为null
            if(updateCategoryBo.getPid() == null){
                return ResponseUtil.fail(-1,"请选择父类目");
            }
            // 如果是一级类目修改为二级类目，确保修改时父类目不是自身
            if(updateCategoryBo.getId().equals(updateCategoryBo.getPid())){
                return ResponseUtil.fail(-1,"父类目不能为自身");
            }
            // 并且要确保当前一级类目下没有二级类目，
            if(children != null && children.size() >0){
                return ResponseUtil.fail(-1,"当前一级类目下有二级类目");
            }

        }
        marketCategoryService.update(updateCategoryBo);
        return ResponseUtil.ok();
    }
    @PostMapping("create")
    public Object create(@RequestBody MarketCategory createCategory) {
        // 参数校验：如果新增的是二级类目，则必须有一个父类目
        Integer pid = createCategory.getPid();
        String level = createCategory.getLevel();
        if (pid == 0 && "L2".equals(level)){
            return ResponseUtil.fail(-1,"必须选择父类目");
        }
        MarketCategory marketCategory = marketCategoryService.create(createCategory);
        return ResponseUtil.ok(marketCategory);
    }
}